package net.yebaihe.wc;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;
import com.mobclick.android.MobclickAgent;

import net.yebaihe.sdk.HttpConnection;
import net.yebaihe.wc.DataMan.MSGTYPE;
import net.yebaihe.wc.MyHelper.DishData;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.content.Intent;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.view.inputmethod.InputMethodManager;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TabHost;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;

public class Dishes extends MapActivity implements StateMachineInterface{

	public static final int NOTIFY_PLACE_CHANGED = 4;
	public static final int NOTIFY_DISMISS_ORDER = 5;
	protected static final int NOTIFY_QUIT_SESSION = 6;
	private ListView lstMenu;
	SQLiteDatabase listdb;
	private ArrayList<Long> pendList=new ArrayList<Long>();
	
	private class SitesOverlay extends ItemizedOverlay<OverlayItem> {
		private List<OverlayItem> items = new ArrayList<OverlayItem>();
		private Drawable marker =null;
		private long id;
		public SitesOverlay(Drawable marker,GeoPoint p, long id) {
			super(marker);
			this.marker = marker;
			this.id=id;
			items.add(new
					OverlayItem(p,null,null));
			populate();
		}
		@Override
		protected OverlayItem createItem(int i) {
			return (items.get(i));
		}
		@Override
		public void draw(Canvas canvas, MapView mapView, boolean shadow) {
			super.draw(canvas, mapView, shadow);
			boundCenterBottom(marker);// 调整一个drawable的边界，使得(0,0)是drawabled底部中心的  //一个像素。
		}
		@Override
		//处理对这个marker的点击事件
		protected boolean onTap(int i) {
			//Toast.makeText(Dishes.this, "你点我干嘛!", Toast.LENGTH_SHORT).show();
			showRestDetail(id);
			return true;
		}
		@Override
		public int size() {
			return (items.size());
		}
	}

	class TalkSimpleCursorAdapter extends SimpleCursorAdapter{

		public TalkSimpleCursorAdapter(Context context, int layout, Cursor c,
				String[] from, int[] to) {
			super(context, layout, c, from, to);
		}
		@Override  
		public void bindView(View view, Context context, Cursor cursor) {  
			super.bindView(view, context, cursor);
			
			Cursor u=listdb.rawQuery("select * from users where _id="+cursor.getLong(2), null);
			if (u.moveToFirst()){
				ImageView v=(ImageView) view.findViewById(R.id.imagethumb);
				File f=new File(getLocalFriendPath(cursor.getInt(2)));
				if (f.exists()){
					v.setImageBitmap(BitmapFactory.decodeFile(f.getAbsolutePath()));
				}
				TextView t=(TextView) view.findViewById(R.id.txtname);
				t.setText(u.getString(3));
			}
			u.close();
			
		}
	}
	
	public String getLocalFriendPath(int id) {
		String basedir=Environment.getExternalStorageDirectory()+"/weican/users/";
		File f=new File(basedir);
		if (!f.exists()) f.mkdirs();
		//Log.d("", basedir+id+".dat");
		return basedir+id+".dat";
	}

	
	public void showRestDetail(long id) {
		btnSMS.setTag(id);
		btnTEL.setTag(id);
		Cursor c=listdb.rawQuery("select * from restaurants where _id="+id, null);
		if (c.moveToFirst()){
			TextView txttitle=(TextView) level3.findViewById(R.id.txttitle);
			txttitle.setText(c.getString(1));
			TextView txtaddr=(TextView) level3.findViewById(R.id.txtaddr);
			txtaddr.setText("地址："+c.getString(10));
			TextView txttel=(TextView) level3.findViewById(R.id.txttel);
			txttel.setText("电话："+c.getString(11));
		}
		c.close();
		level3.setVisibility(View.VISIBLE);
	}


	class AssetToSDRunnable implements Runnable{

		private int id;

		public AssetToSDRunnable(int id) {
			this.id=id;
		}

		@Override
		public void run() {
			AssetManager am = Dishes.this.getAssets();
			try {
				InputStream is = am.open(id+".dat");
				String path=getLocalDishPath(id);
				File fd=new File(path);
				if (!fd.exists()){
					FileOutputStream os = new FileOutputStream(path);
					byte[] buf = new byte[1024];
					int n = 0;
					int o = 0;
					while ((n = is.read(buf, o, buf.length)) != -1) {
						os.write(buf, 0, n);
					}
					is.close();
					os.close();
				}

				File ft=new File(path+".thumb");
				if (!ft.exists()){
					Bitmap thumb=Bitmap.createScaledBitmap(BitmapFactory.decodeFile(path), 50, 50, true);
					try {
						FileOutputStream out = new FileOutputStream(path+".thumb");
						thumb.compress(Bitmap.CompressFormat.PNG, 90, out);
						out.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
					refreshListMenu();
				}
				
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}
	
	public Handler dishImgHandler=new Handler(){
		public void handleMessage(Message message) {
     		switch (message.what) {
     		case HttpConnection.DID_START: {
     			break;
     		} 
     		case HttpConnection.DID_SUCCEED: {
     			String path=(String) message.obj;
				Bitmap thumb=Bitmap.createScaledBitmap(BitmapFactory.decodeFile(path), 50, 50, true);
     			try {
     				FileOutputStream out = new FileOutputStream(path+".thumb");
     				thumb.compress(Bitmap.CompressFormat.PNG, 90, out);
     				out.close();
     			} catch (Exception e) {
     				e.printStackTrace();
     			}
     			refreshListMenu();
     			break;
     		}
     		}
		}
	};
	private ArrayList<TextView> allTags=new ArrayList<TextView>();
	private String currSql="";
	private TextView txtBtnOrder;
	private ListView lstOrder;
	private TextView txtTotal;
	private Button btnInvite;
	private Button btnOrderFinish;
	private boolean pendingInvite=false;
	private long sessionUser;
	private EditText edtTalk;
	private ListView lstTalk;

	/* come from state machine */
	
	LinearLayout topbar;
	private View client;
	ImageView imglevel2;
	LinearLayout level2;
	private boolean checking=false;
	private MapView mapView;
	private LinearLayout level3;
	private View resdetail;
	private Button btnSMS;
	private Button btnTEL;
	private TabHost tabHost;
	private Gallery galleryPeople;

	protected WCApp getWCAppContext() {
		return (WCApp)this.getApplicationContext();
	}

	public void onResume() {
	    super.onResume();
	    MobclickAgent.onResume(this);
	    updateTopBar();
        if (this.getWCAppContext().email.length()>0) DataMan.get(this).checkNotifies();
        checkLeftSession();
        getWCAppContext().curStateMachine=this;
		onSessionChange();
		if (!checkSessionValid()){
			if (tabHost.getCurrentTab()==1){
				tabHost.setCurrentTab(0);
			}
		}
		updateBtnOrderLabel();
	}
	public void onPause() {
	    super.onPause();
	    MobclickAgent.onPause(this);
        getWCAppContext().curStateMachine=null;
	}

    protected void changeToActivity(@SuppressWarnings("rawtypes") Class target){
		Intent intent=new Intent(this,target);
		intent.putExtra("lasttitle", getTopbarTitle());
		if (target==Dishes.class){
			intent.putExtra("restaurant", getWCAppContext().restaurant);
		}
		else if (target==ShowSessionDetail.class){
			intent.putExtra("sessionid", getWCAppContext().sessionid);
		}
		else if (target==SNS.class){
			intent.putExtra("sessionid", getWCAppContext().sessionid);
		}
		startActivity(intent);
		if (target==Login.class){
			overridePendingTransition(R.anim.down_in,R.anim.down_out); 
		}
    }
    
    protected void updateTopBar() {
    	TextView txtTitle=(TextView) topbar.findViewById(R.id.txtTitle);
    	txtTitle.setText(getMost(getTopbarTitle(),5));
    	txtTitle.setTextColor(0xFFFFFFFF);
    	
    	Button txtLeft=(Button)topbar.findViewById(R.id.btnleft);
    	TextView txtMessage=(TextView)topbar.findViewById(R.id.txtMessage);
    	txtMessage.setText("");
    	String lastTitle=getIntent().getStringExtra("lasttitle");
    	if ((lastTitle!=null) && (lastTitle.length()>0)){
    		txtLeft.setText(getMost(lastTitle,3));
    		txtLeft.setOnClickListener(new OnClickListener(){
				@Override
				public void onClick(View arg0) {
					goback();
				}
    		});
    	}
    	else{
    		txtLeft.setText(getWCAppContext().city);
    		txtLeft.setOnClickListener(new OnClickListener(){
				@Override
				public void onClick(View v) {
					changeToActivity(Cities.class);
				}
    		});
    	}
    	
    	Button btnRight=(Button)topbar.findViewById(R.id.btnRight);
    	if (getWCAppContext().email.length()>0){
    		if (getWCAppContext().notifications==0){
        		btnRight.setBackgroundResource(R.drawable.p_mail);
    	   		btnRight.setText(""+getWCAppContext().notifications);
    	   		btnRight.setEnabled(false);
    		}
    		else{
    	   		btnRight.setEnabled(true);
        		btnRight.setBackgroundResource(R.drawable.p_mail);
    	   		btnRight.setText(""+getWCAppContext().notifications);
        		btnRight.setOnClickListener(new OnClickListener(){
    				@Override
    				public void onClick(View v) {
    		    		changeToActivity(Notifications.class);
    				}
        		});
    		}
     	}
    	else{
    		btnRight.setBackgroundResource(R.drawable.b_logd);
	   		btnRight.setText("");
    		btnRight.setOnClickListener(new OnClickListener(){
				@Override
				public void onClick(View v) {
					changeToActivity(Login.class);
				}
    		});
    	}
    	
    	
    	txtLeft.setTextColor(0xFFFFFFFF);
    	LinearLayout bg=(LinearLayout)topbar.findViewById(R.id.layoutbg);
        bg.setBackgroundResource(R.drawable.bg_2top);
	}

	private CharSequence getMost(String lastTitle, int i) {
		if (lastTitle.length()>i){
			return lastTitle.substring(0, i)+"...";
		}
		return lastTitle;
	}

	protected void showBigImage(String path) {
		imglevel2.setImageBitmap(BitmapFactory.decodeFile(path));
		level2.setVisibility(View.VISIBLE);
		Animation am1 = new AlphaAnimation ( 0, 1 );
		am1. setDuration ( 1000 );
		Animation am2=new ScaleAnimation(0, 1, 0, 1);
		am2. setDuration ( 1000 );
		AnimationSet am = new AnimationSet ( false );
		am.addAnimation(am1);
		am.addAnimation(am2);
		level2.startAnimation(am);
	}    
    
	private String getCurrentCity() {
		WCApp app=(WCApp)this.getApplicationContext();
		if (app.city.length()<=0){
			app.city="北京";
		}
		return app.city;
	}

	protected void checkLeftSession() {
		if (getWCAppContext().sessionid>0) return;
		if (getWCAppContext().email.length()<=0) return;
		if (checking) return;
		checking=true;
		UserInfoData userinfo = MyHelper.get(this).getCurrUserInfoData(getWCAppContext().email);
		SQLiteDatabase db = MyHelper.get(this).getReadableDatabase();
		Cursor c=db.rawQuery("select * from sessions where fromuid="+userinfo._id+" and state=1", null);
		if (c.moveToLast()){
			final long sessionid=c.getLong(0);
			final int restaurant=c.getInt(4);
			new AlertDialog.Builder(this).setTitle("继续点餐").setIcon(R.drawable.icon).setMessage("你上次发起的聚餐活动没有完成，要继续吗？")
				.setPositiveButton("继续点餐", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						getWCAppContext().sessionid=(int) sessionid;
						getWCAppContext().restaurant=restaurant;
						changeToActivity(Dishes.class);
						checking=false;
					}
				})
				.setNegativeButton("放弃本次点餐", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						SQLiteDatabase wdb = MyHelper.get(Dishes.this).getWritableDatabase();
						wdb.delete("sessions", "_id="+sessionid, null);
						wdb.delete("sessiondish", "sessionid="+sessionid, null);
						wdb.delete("sessionuser", "sessionid="+sessionid, null);
						wdb.close();
						Toast.makeText(Dishes.this, "点餐已放弃", Toast.LENGTH_SHORT).show();
						checking=false;
					}
				})
				.setCancelable(false)
				.create().show();
		}
		c.close();
		db.close();
	}		
	
	protected boolean checkLogin(boolean redirect) {
		if (this.getWCAppContext().email.length()<=0){
			if (redirect){
				changeToActivity(Login.class);
			}
			return false;
		}
		return true;
	}	
	
	protected void goback() {
			super.onBackPressed();
	}
	
	@Override 
	public void onBackPressed(){
		//Log.d("", "back pressed on dishes:"+level3.getVisibility());
		if (level2.isShown()){
			level2.setVisibility(View.GONE);
		}
		else{
			finish();
		}
	}

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.getWCAppContext().init();
        Log.d("myown", this.getClass().getName());
        FrameLayout layout=new FrameLayout(this);
        LinearLayout main=new LinearLayout(this);
        main.setOrientation(LinearLayout.VERTICAL);
        main.setBackgroundResource(R.drawable.bg_1);
        topbar=(LinearLayout) View.inflate(this, R.layout.topbar, null);
        updateTopBar();
        client=View.inflate(this, getLayoutRes(), null);
        LinearLayout.LayoutParams p=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.FILL_PARENT);
        main.addView(topbar);
        main.addView(client,p);
        layout.addView(main,new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
        
        level2=new LinearLayout(this);
        imglevel2=new ImageView(this);
        level2.setGravity(Gravity.CENTER);
        level2.addView(imglevel2,new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
        layout.addView(level2);
        level2.setVisibility(View.GONE);
        level2.setBackgroundColor(0x88c8c8c8);
        level2.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				level2.setVisibility(View.GONE);
			}
        });

        level3=new LinearLayout(this);
        resdetail=View.inflate(this, R.layout.resdetail, null);
        level3.addView(resdetail);
        level3.setGravity(Gravity.CENTER);
        layout.addView(level3);
        btnSMS=(Button)level3.findViewById(R.id.btnsms);
        btnSMS.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				long id=(Long) arg0.getTag();
				Cursor c=listdb.rawQuery("select * from restaurants where _id="+id, null);
				if (c.moveToFirst()){
					Intent it = new Intent(Intent.ACTION_VIEW);    
					it.putExtra("sms_body", c.getString(1)+"地址:"+c.getString(10)+" 电话:"+c.getString(11));    
					it.setType("vnd.android-dir/mms-sms");    
					startActivity(it);   
				}
				c.close();
			}
        });
        btnTEL=(Button)level3.findViewById(R.id.btntel);
        btnTEL.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				long id=(Long) arg0.getTag();
				Cursor c=listdb.rawQuery("select * from restaurants where _id="+id, null);
				if (c.moveToFirst()){
					Intent intent = new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+c.getString(11)));		    
					startActivity(intent);			
				}
				c.close();
			}
        });
        
        level3.setVisibility(View.GONE);
        //level3.setBackgroundColor(0x88c8c8c8);
        level3.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				level3.setVisibility(View.GONE);
			}
        });
        
        
        setContentView(layout);
        prepareClient(client);
        if (this.getWCAppContext().email.length()>0) DataMan.get(this).checkNotifies();

        mapView = (MapView) client.findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
        
    }
    /* end state machine */
    
    
	class OrderSimpleCursorAdapter extends SimpleCursorAdapter{

		public OrderSimpleCursorAdapter(Dishes dishes, int itemdish, Cursor c,
				String[] strings, int[] is) {
			super(dishes,itemdish,c,strings,is);
		}
		
		@Override  
		public void bindView(View view, Context context, Cursor cursor) {  
			super.bindView(view, context, cursor);

			if (cursor.getPosition() % 2==0){
				//view.setBackgroundColor(R.drawable);
				view.setBackgroundResource(R.drawable.rest_bg_1);
			}
			else{
				//view.setBackgroundColor(0xFFdde4f6);
				view.setBackgroundResource(R.drawable.rest_bg_2);

			}
			
			ImageView img=(ImageView) view.findViewById(R.id.imagethumb);
			img.setTag(getLocalDishPath(cursor.getInt(0)));
			img.setOnClickListener(new OnClickListener(){
				@Override
				public void onClick(View arg0) {
					Log.d("", arg0.getTag().toString());
					showBigImage(arg0.getTag().toString());
				}
			});
			File f=new File(getLocalDishPath(cursor.getInt(0))+".thumb");
			if (f.exists()){
				img.setImageBitmap(BitmapFactory.decodeFile(f.getAbsolutePath()));
			}
			else{
				new Handler().postDelayed(new AssetToSDRunnable(cursor.getInt(0)), 100);
			}
			
			if (listdb!=null){
				Cursor c=listdb.rawQuery("select * from sessiondish where sessionid="+getWCAppContext().sessionid+" and dishid="+cursor.getLong(0), null);
				c.moveToFirst();
				UserInfoData userinfo = MyHelper.get(Dishes.this).getCurrUserInfoData(c.getLong(2));
				String t=userinfo.username+"改为"+c.getInt(5)+"份";
				TextView v=(TextView) view.findViewById(R.id.txtorders);
				v.setText(Html.fromHtml(t));
				c.close();
			}
			
		}
	}

	
	class DishSimpleCursorAdapter extends SimpleCursorAdapter{

		public DishSimpleCursorAdapter(Dishes dishes, int itemdish, Cursor c,
				String[] strings, int[] is) {
			super(dishes,itemdish,c,strings,is);
		}
		
		@Override  
		public void bindView(View view, Context context, Cursor cursor) {  
			super.bindView(view, context, cursor);

			if (cursor.getPosition() % 2==0){
				//view.setBackgroundColor(R.drawable);
				view.setBackgroundResource(R.drawable.rest_bg_1);
			}
			else{
				//view.setBackgroundColor(0xFFdde4f6);
				view.setBackgroundResource(R.drawable.rest_bg_2);

			}
			
			TextView ts=(TextView)view.findViewById(R.id.txttimeinsession);
			Cursor ss=listdb.rawQuery("select * from sessions where _id="+getWCAppContext().sessionid, null);
			ts.setText("");
			if (ss.moveToFirst()){
				if (ss.getInt(5)==1){
					Cursor cc=listdb.rawQuery("select sum(total) from sessiondish where sessionid="+getWCAppContext().sessionid+" and dishid="+cursor.getInt(0), null);
					if (cc.moveToFirst()){
						if (cc.getInt(0)>0){
							ts.setText(cc.getString(0));
						}
					}
					cc.close();
				}
			}
			ss.close();
			
			ImageView img=(ImageView) view.findViewById(R.id.imagethumb);
			img.setTag(getLocalDishPath(cursor.getInt(0)));
			img.setOnClickListener(new OnClickListener(){
				@Override
				public void onClick(View arg0) {
					Log.d("", arg0.getTag().toString());
					showBigImage(arg0.getTag().toString());
				}
			});
			File f=new File(getLocalDishPath(cursor.getInt(0))+".thumb");
			if (f.exists()){
				img.setImageBitmap(BitmapFactory.decodeFile(f.getAbsolutePath()));
			}
			else{
				//从网址获取图片
				//File f1=new File(getLocalDishPath(cursor.getInt(0)));
				//if (!f1.exists())
				//	new HttpConnection(Dishes.this, dishImgHandler).file(cursor.getString(7), getLocalDishPath(cursor.getInt(0)));
				
				//Offline version get image from assets
				new Handler().postDelayed(new AssetToSDRunnable(cursor.getInt(0)), 100);
			}
		}
	}
	
	@Override
	public void HandleMessage(MSGTYPE msgtype, boolean ret,
			HashMap<String, String> params) {
		switch (msgtype){
		case CITY_CHANGE:
		{
			this.updateTopBar();
		}
			break;
		case CHECK_NOTIFICATIONS:
		{
			UserInfoData userdata = MyHelper.get(this).getCurrUserInfoData(getWCAppContext().email);
			if (userdata!=null){
				SQLiteDatabase db = MyHelper.get(this).getWritableDatabase();
				if (db!=null){
					db.delete("notifications", "type="+StateMachine.NOTIFY_LEFT_SESSION+" and userdata='"+getWCAppContext().sessionid+"'", null);
					Cursor c=db.rawQuery( 
							"SELECT count(*) FROM notifications WHERE done=0 and touid="+userdata._id, null);
					if (c.moveToFirst()){
						getWCAppContext().notifications=c.getInt(0);
						this.updateTopBar();
					}
					c.close();
					db.close();
				}
			}
		}
			break;
		case CONFIRM_ORDER:{
			Toast.makeText(this, "点餐已确认", Toast.LENGTH_SHORT).show();
			UserInfoData data = MyHelper.get(this).getCurrUserInfoData(getWCAppContext().email);
			Cursor s=listdb.rawQuery("select * from restaurants where _id in (select restaurant from sessions where _id="+getWCAppContext().sessionid+")",null);
			s.moveToFirst();
			Cursor c=listdb.rawQuery("select uid from sessionuser where uid != "+data._id+" and  sessionid="+getWCAppContext().sessionid, null);
			while (c.moveToNext()){
				MyHelper.get(this).insertNotify(data._id, c.getLong(0), s.getString(1)+"点餐已结束", 3, ""+getWCAppContext().sessionid);
			}
			c.close();
			s.close();
			changeToActivity(ShowSessionDetail.class);
		}
			break;
		case ADD_SESSION:
			if (ret){
				this.getWCAppContext().sessionid=Integer.parseInt(params.get("id"));
				addPendingOrders();
				onSessionChange();
				if (pendingInvite){
					pendingInvite=false;
					changeToActivity(Friends.class);
				}
			}
			break;
		case ADD_ORDER:
			if (ret){
				long id=Long.parseLong(params.get("dish"));
				DishData data=MyHelper.get(this).getDishInfo(id);
				Toast.makeText(this, data.name+"已点", Toast.LENGTH_SHORT).show();
				updateBtnOrderLabel();
				this.refreshListMenu();
				onSessionChange();
			}
			else{
				Toast.makeText(this, "点餐失败："+params.get("reason"), Toast.LENGTH_SHORT).show();
			}
			break;
		case TALK:
			refreshTalkList();
			break;
		}
		
	}
	
	class peopleGalleryAdapter  extends BaseAdapter {
		private Context context; // needed to create the view
		public peopleGalleryAdapter(Context c) {
			context = c;
		}
		public int getCount() {
			Cursor c=listdb.rawQuery("select count(*) from sessionuser where sessionid="+getWCAppContext().sessionid, null);
			c.moveToFirst();
			int total=c.getInt(0);
			//Toast.makeText(Dishes.this, "total:"+(total+1), Toast.LENGTH_SHORT).show();
			c.close();
			return total+1;
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View v;
			if(convertView == null){
				v = LayoutInflater.from(context).inflate(R.layout.itemgalpeople, parent, false);
			}
			else
				v = convertView;
			TextView tv = (TextView) v.findViewById(R.id.txtname);
			ImageView iv=(ImageView) v.findViewById(R.id.imgphoto);
			
			Cursor c;
			if (position==0){
				c=listdb.rawQuery("select * from users where _id in (select fromuid from sessions where _id="+getWCAppContext().sessionid+")", null);
			}
			else{
				c=listdb.rawQuery("select * from users where _id in (select uid from sessionuser where sessionid="+getWCAppContext().sessionid+" limit "+(position-1)+",1)", null);
			}
			if (c.moveToFirst()){
				tv.setText(c.getString(3));
				File f=new File(getLocalFriendPath(c.getInt(0)));
				if (f.exists()){
					iv.setImageBitmap(BitmapFactory.decodeFile(f.getAbsolutePath()));
				}
				else{
					//TODO new HttpConnection(Friends.this, friendImgHandler).file(getUserThumbUrl(cursor.getLong(0)), getLocalFriendPath(cursor.getInt(0)));
				}
			}
			c.close();
			
			return v;
		}
	}

	private void refreshTalkList() {
		if (listdb!=null){
			Cursor c=listdb.rawQuery("select count(*) from talk where sessionid="+getWCAppContext().sessionid, null);
			c.moveToFirst();
			int start=0;
			if (c.getInt(0)>50){
				start=c.getInt(0)-50;
			}
			c.close();
			c=listdb.rawQuery("select * from talk where sessionid="+getWCAppContext().sessionid+" order by _id limit "+start+",50 ", null);
			
			startManagingCursor(c);
			ListAdapter listAdapter = new TalkSimpleCursorAdapter(this, R.layout.itemtalk,
					c,
					new String[]{"cnt"},
					new int[]{R.id.txtmessage});
			lstTalk.setAdapter(listAdapter);
			lstTalk.post(new Runnable(){
				public void run() {
					lstTalk.setSelection(lstTalk.getCount() - 1);
					edtTalk.setText("");
				}});
		}
	}

	private void updateBtnOrderLabel() {
		txtBtnOrder.setText("已点");
		Cursor c=listdb.rawQuery("select * from sessions where _id="+getWCAppContext().sessionid, null);
		if (c.moveToFirst()){
			if (c.getInt(5)==1){
				int total=MyHelper.get(this).getSessionDishCount(Dishes.this.getWCAppContext().sessionid);
				if (total>0){
					txtBtnOrder.setText("已点（"+total+"）");
				}
			}
		}
		c.close();
	}

	private void addPendingOrders() {
		for (int i=0;i<pendList.size();i++){
			UserInfoData data = MyHelper.get(Dishes.this).getCurrUserInfoData(Dishes.this.getWCAppContext().email);
			DataMan.get(Dishes.this).addOrder(Dishes.this.getWCAppContext().sessionid,pendList.get(0),data._id);
		}
		pendList.clear();
	}

	public String getLocalDishPath(int id) {
		String basedir=Environment.getExternalStorageDirectory()+"/weican/dishes/"+getWCAppContext().restaurant+"/";
		File f=new File(basedir);
		if (!f.exists()) f.mkdirs();
		//Log.d("", basedir+id+".dat");
		return basedir+id+".dat";
	}

	protected String getTopbarTitle() {
		String title="某某餐厅";
		SQLiteDatabase db = MyHelper.get(this).getReadableDatabase();
		if (db!=null){
			Cursor c=db.rawQuery( 
				     "SELECT * FROM restaurants WHERE _id="+getWCAppContext().restaurant, null);
			if (c.moveToFirst()){
				title=c.getString(1);
			}
			c.close();
			db.close();
		}
		return title;
	}

	private GeoPoint getGeoPoint(double lon, double lat) { 
        return new GeoPoint((int) (lat * 1e6), 
                (int) (lon * 1e6)); 
    }

	
	protected void prepareClient(View client) {
		listdb=MyHelper.get(this).getReadableDatabase();
		currSql="select *, price || '元' as price,'下单量: '||ordertimes||' 次' as ordertimes from dishes where restaurant="+getWCAppContext().restaurant;
		
        View btnMenu=LayoutInflater.from(this).inflate(R.layout.btnmenu, null);
        View btnOrder=LayoutInflater.from(this).inflate(R.layout.btnorder, null);
        txtBtnOrder=(TextView) btnOrder.findViewById(R.id.txtBtnOrder);
        View btnSession=LayoutInflater.from(this).inflate(R.layout.btnsession, null);
		View btnMap=LayoutInflater.from(this).inflate(R.layout.btnmap,null);
        
        LinearLayout tab1=(LinearLayout)this.findViewById(R.id.tab1);
        LinearLayout layoutMenu = (LinearLayout)LayoutInflater.from(this).inflate(R.layout.layoutmenu, null);
		lstMenu=(ListView) layoutMenu.findViewById(R.id.lstMenu);
        tab1.addView(layoutMenu,new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.FILL_PARENT));      
        refreshListMenu();

		SQLiteDatabase db = MyHelper.get(this).getWritableDatabase();
		if (db!=null){
			LinearLayout layoutScrollTop=(LinearLayout) layoutMenu.findViewById(R.id.layoutScrollTop);
			TextView t=addTag("全部",layoutScrollTop);
			t.setBackgroundResource(R.drawable.slide_light);
			Cursor c=db.rawQuery("SELECT distinct style FROM dishes where restaurant="+getWCAppContext().restaurant, null);
			if (c.moveToFirst()){
				do{
					addTag(c.getString(0),layoutScrollTop);
				}while (c.moveToNext());
			}
			c.close();
			db.close();
		}
        
        LinearLayout tab3=(LinearLayout)this.findViewById(R.id.tab3);
        LinearLayout layoutSession = (LinearLayout)LayoutInflater.from(this).inflate(R.layout.layoutsession, null);
        tab3.addView(layoutSession,new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.FILL_PARENT));  
        edtTalk=(EditText)layoutSession.findViewById(R.id.edttalk);
        lstTalk=(ListView)layoutSession.findViewById(R.id.lstTalk);
        galleryPeople=(Gallery)layoutSession.findViewById(R.id.galpeople);
        Button btnSend = (Button)layoutSession.findViewById(R.id.btnsend);
        btnSend.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				doTalk();
			}
        });
        edtTalk.setOnEditorActionListener(new OnEditorActionListener(){
			@Override
			public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
				if (arg2!=null){
					doTalk();
				}
				return false;
			}
        });

        LinearLayout tab2=(LinearLayout)this.findViewById(R.id.tab2);
        LinearLayout layoutOrder = (LinearLayout)LayoutInflater.from(this).inflate(R.layout.layoutorder, null);
        tab2.addView(layoutOrder,new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.FILL_PARENT));  
        lstOrder=(ListView) layoutOrder.findViewById(R.id.lstorder);
        txtTotal=(TextView)layoutOrder.findViewById(R.id.txtTotal);
        btnInvite=(Button)layoutOrder.findViewById(R.id.btninvite);
        btnInvite.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				if (getWCAppContext().email.length()<=0){
					changeToActivity(Login.class);
					return;
				}
				getWCAppContext().inviteInFriends=true;
				if (getWCAppContext().sessionid<=0){
					pendingInvite=true;
					UserInfoData userinfo = MyHelper.get(Dishes.this).getCurrUserInfoData(getWCAppContext().email);
					DataMan.get(Dishes.this).addNewSession(userinfo._id, getWCAppContext().restaurant);
				}
				else{
					changeToActivity(Friends.class);
				}
			}
        });
        btnOrderFinish=(Button)layoutOrder.findViewById(R.id.btnOrderFinish);
        onSessionChange();
        btnOrderFinish.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				int total=MyHelper.get(Dishes.this).getSessionDishCount(Dishes.this.getWCAppContext().sessionid);
				if (total<=0){
					new AlertDialog.Builder(Dishes.this).setTitle(R.string.app_name).setMessage("可是您还什么都没点呢？！").setPositiveButton("确定", null).create().show();
					return;
				}

				
				new AlertDialog.Builder(Dishes.this).setIcon(R.drawable.icon).setTitle("确认点餐完成")
					.setMessage("确认以后，所有人都不能再点餐，你确定已完成点餐吗？")
					.setPositiveButton("是", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface arg0, int arg1) {
							String sessiontitle=getTopbarTitle()+"聚餐";
							DataMan.get(Dishes.this).confirmOrder(getWCAppContext().sessionid,sessiontitle);
							/*final EditText t=new EditText(Dishes.this);
							new AlertDialog.Builder(Dishes.this).setTitle("请输入聚餐标题：").setIcon(R.drawable.icon)
								.setView(t)
								.setPositiveButton("确定", new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface arg0, int arg1) {
									}
								})
								.setNegativeButton("取消", null).create().show();*/
						}
					})
					.setNegativeButton("否", null).create().show();
			}
        });
		
        LinearLayout tab4=(LinearLayout)this.findViewById(R.id.tab4);
        LinearLayout layoutMap = (LinearLayout)LayoutInflater.from(this).inflate(R.layout.layoutmap, null);
        tab4.addView(layoutMap,new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.FILL_PARENT));        

        
        tabHost=(TabHost) client.findViewById(R.id.tabhost);
        tabHost.setup();
        tabHost.addTab(tabHost.newTabSpec("menu").setContent(R.id.tab1).setIndicator(btnMenu));
        tabHost.addTab(tabHost.newTabSpec("order").setContent(R.id.tab2).setIndicator(btnOrder));
        tabHost.addTab(tabHost.newTabSpec("session").setContent(R.id.tab3).setIndicator(btnSession));
        tabHost.addTab(tabHost.newTabSpec("map").setContent(R.id.tab4).setIndicator(btnMap));
        tabHost.setOnTabChangedListener(new OnTabChangeListener(){
			@Override
			public void onTabChanged(String tabId) {
				InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(edtTalk.getWindowToken(), 0);
				if (tabId.equals("order")){
					refreshOrder();
				}
				else if (tabId.equals("session")){
					galleryPeople.setAdapter(new peopleGalleryAdapter(Dishes.this));
					refreshTalkList();
				}
				else if (tabId.equals("map")){
					Cursor c=listdb.rawQuery("select * from restaurants where _id="+getWCAppContext().restaurant, null);
					if (c.moveToFirst()){
						mapView.getController().setZoom(17);
						GeoPoint geoPoint = getGeoPoint(c.getDouble(5),c.getDouble(6));
						mapView.getController().animateTo(geoPoint);
						
						mapView.getOverlays().clear();
						Drawable marker=getResources().getDrawable(R.drawable.b_sendd);//在资源中选择一个图片
						marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker.getIntrinsicHeight());
						mapView.getOverlays().add(new SitesOverlay(marker,geoPoint,c.getLong(0)));
					
					}
					c.close();
				}
			}
        });
        tabHost.setCurrentTab(0);
        updateBtnOrderLabel();     
        
        if (getWCAppContext().pendingOrder>=0){
        	orderDish(getWCAppContext().pendingOrder);
        	getWCAppContext().pendingOrder=-1;
        }
	}
	
	private void orderDish(long id) {
		final long dishid=id;
		if (Dishes.this.getWCAppContext().email.length()<=0){
			changeToActivity(Login.class);
			return;
		}
		if (Dishes.this.getWCAppContext().sessionid==-1){
			pendingOrder(id);
			UserInfoData data = MyHelper.get(Dishes.this).getCurrUserInfoData(Dishes.this.getWCAppContext().email);
			DataMan.get(Dishes.this).addNewSession(data._id,getWCAppContext().restaurant);
		}
		else{
			final Cursor c=listdb.rawQuery("select * from sessions where _id="+Dishes.this.getWCAppContext().sessionid, null);
			if (c.moveToFirst()){
				if (c.getInt(5)==2){//点某个菜但是点餐已经结束。
					Toast.makeText(Dishes.this, "你正在发起一个新的聚餐！", Toast.LENGTH_SHORT).show();
					Dishes.this.getWCAppContext().sessionid=-1;
					UserInfoData data = MyHelper.get(Dishes.this).getCurrUserInfoData(Dishes.this.getWCAppContext().email);
					pendingOrder(id);
					DataMan.get(Dishes.this).addNewSession(data._id,getWCAppContext().restaurant);
				}
				else{
					final long oldrestaurant=c.getLong(4);
					if (oldrestaurant!=getWCAppContext().restaurant){//在和当前会话不同的地方点餐
						UserInfoData data = MyHelper.get(Dishes.this).getCurrUserInfoData(Dishes.this.getWCAppContext().email);
						if (c.getLong(1) != data._id){//不是当前点餐会话的发起人不能修改订餐地点
							askJoinerIfQuit(c,dishid);
							//Toast.makeText(Dishes.this, "您不能在这个餐馆点餐", Toast.LENGTH_SHORT).show();
						}
						else{
							askDifferentRestaurantChoice(oldrestaurant,dishid);
						}
					}
					else{
						if (Dishes.this.getWCAppContext().sessionid==-1){
							pendingOrder(id);
						}
						else{
							Cursor d=listdb.rawQuery("select * from  sessiondish where dishid="+id+" and sessionid="+Dishes.this.getWCAppContext().sessionid, null);
							if (d.moveToFirst()){
								Toast.makeText(Dishes.this, "此菜已点，修改份数请长按", Toast.LENGTH_SHORT).show();
							}
							else {
								UserInfoData data = MyHelper.get(Dishes.this).getCurrUserInfoData(Dishes.this.getWCAppContext().email);
								DataMan.get(Dishes.this).addOrder(Dishes.this.getWCAppContext().sessionid,id,data._id);
							}
							d.close();
						}
					}
				}
			}
			c.close();
		}
	}


	protected void doTalk() {
		if (getWCAppContext().email.length()<0){
			changeToActivity(Login.class);
			return;
		}
		
		if (getWCAppContext().sessionid<=0){
			Toast.makeText(Dishes.this, "您需要先发起一个点餐活动才可以使用聊天功能！", Toast.LENGTH_SHORT).show();
			return;
		}
		
		String cnt=edtTalk.getText().toString();
		if (cnt.length()<=0) return;
		
		UserInfoData userdata = MyHelper.get(Dishes.this).getCurrUserInfoData(getWCAppContext().email);
		DataMan.get(Dishes.this).insertTalkCnt(userdata._id,getWCAppContext().sessionid,cnt);
		
	}


	protected boolean checkSessionValid() {
		Cursor c=listdb.rawQuery("select * from sessions where _id="+getWCAppContext().sessionid, null);
		if (c.moveToFirst()){
			if (c.getInt(5)==1){
				c.close();
				return true;
			}
		}
		c.close();
		return false;
	}


	private void onSessionChange() {
		btnOrderFinish.setEnabled(true);
		btnInvite.setEnabled(true);
        Cursor s=listdb.rawQuery("select * from sessions where _id="+getWCAppContext().sessionid, null);
        UserInfoData userdata = MyHelper.get(this).getCurrUserInfoData(getWCAppContext().email);
        if (s.moveToFirst()){
        	sessionUser=s.getLong(1);
        	if (sessionUser!=userdata._id){
        		btnOrderFinish.setEnabled(false);
        	}
        	else if (s.getInt(5)==2){
        		btnInvite.setEnabled(false);
        		btnOrderFinish.setEnabled(false);
        	}
        }
        else{
    		btnOrderFinish.setEnabled(false);
        }
        s.close();
	}

	protected void refreshOrder() {
		if (listdb!=null){
			int sessionid= this.getWCAppContext().sessionid;
			if (!checkSessionValid()){
				sessionid=-1;
			}
			Cursor c=listdb.rawQuery("select dishes._id,dishes.name,'' || count || ' * ' || dishes.price || '元' as count  from (select *,sum(total) as count from sessiondish where sessionid="
							+sessionid+" group by dishid) as ta,dishes where ta.dishid=dishes._id", null);
			startManagingCursor(c);
			ListAdapter listAdapter = new OrderSimpleCursorAdapter(this, R.layout.itemorder,
					c,
					new String[]{"name","count"},
					new int[]{R.id.txtname,R.id.txtprice});
			lstOrder.setAdapter(listAdapter);
			lstOrder.setOnItemLongClickListener(new OnItemLongClickListener(){
				@Override
				public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					showSessionDishModifyDialog(arg3);
					return false;
				}
			});
			lstOrder.setOnItemClickListener(new OnItemClickListener(){
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					final long dishid=arg3;
					Cursor d=listdb.rawQuery("select * from dishes where _id="+dishid, null);
					d.moveToFirst();
					new AlertDialog.Builder(Dishes.this).setTitle("删除订单").setIcon(R.drawable.icon)
						.setMessage("你确实要删除 "+d.getString(2)+" 吗？")
						.setPositiveButton("确定", new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface arg0, int arg1) {
								SQLiteDatabase db = MyHelper.get(Dishes.this).getWritableDatabase();
								db.delete("sessiondish", "sessionid="+getWCAppContext().sessionid+" and dishid="+dishid, null);
								db.close();
								refreshOrder();
								Dishes.this.updateBtnOrderLabel();
							}
						})
						.setNegativeButton("取消", null).create().show();
					d.close();
				}
			});
			
			Cursor t=listdb.rawQuery("select sum(count*price) as sum from (select  count,price from (select *,sum(total) as count from sessiondish where sessionid="
							+sessionid+" group by dishid) as ta,dishes where ta.dishid=dishes._id)", null);
			t.moveToFirst();
			txtTotal.setText("总价 "+t.getDouble(0)+" 元");
			t.close();
		}
	}

	private TextView addTag(String string, LinearLayout layoutScrollTop) {
		TextView t=new TextView(this);
		t.setText(string);
		t.setTag(string);
		t.setGravity(Gravity.CENTER);
		allTags.add(t);
		LinearLayout.LayoutParams p=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.FILL_PARENT);
		p.rightMargin=10;
		p.leftMargin=10;
		t.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				for (int i=0;i<allTags.size();i++){
					allTags.get(i).setBackgroundColor(0x00000000);
				}
				v.setBackgroundResource(R.drawable.slide_light);
				String l=v.getTag().toString();
				if (l.equals("全部")){
					currSql="select *, price || '元' as price,'下单量: '||ordertimes||' 次' as ordertimes from dishes where restaurant="+getWCAppContext().restaurant;
				}
				else{
					currSql="select *, price || '元' as price,'下单量: '||ordertimes||' 次' as ordertimes from dishes where style='"+v.getTag().toString()+"' and restaurant="+getWCAppContext().restaurant;
				}
				refreshListMenu();
			}
		});
		layoutScrollTop.addView(t,p);
		return t;
	}

	private void refreshListMenu() {
		if (listdb!=null){
			
			final int selpos=lstMenu.getLastVisiblePosition();
			
			Cursor c=listdb.rawQuery(currSql, null);
			startManagingCursor(c);
			
			if (lstMenu.getAdapter()==null){
				ListAdapter listAdapter = new DishSimpleCursorAdapter(this, R.layout.itemdish,
						c,
						new String[]{"name","price","ordertimes"},
						new int[]{R.id.txtname,R.id.txtprice,R.id.txtorders});
				lstMenu.setAdapter(listAdapter);
			}
			else{
				DishSimpleCursorAdapter adapt=(DishSimpleCursorAdapter) lstMenu.getAdapter();
				adapt.changeCursor(c);
			}
			
			lstMenu.setOnItemLongClickListener(new OnItemLongClickListener(){
				@Override
				public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					showSessionDishModifyDialog(arg3);
					return false;
				}
			});
			
			lstMenu.setOnItemClickListener(new OnItemClickListener(){
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long id) {
					orderDish(id);
				}
			});
			
		}
	}

	protected void askJoinerIfQuit(Cursor c, long id) {
		final long sessionid=c.getLong(0);
		final long dishid=id;
		final long sessionowner=c.getLong(1);
		new AlertDialog.Builder(this).setTitle("退出聚餐")
			.setMessage("您确定要退出当前聚餐，独自在新餐厅点餐吗？")
			.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					UserInfoData data = MyHelper.get(Dishes.this).getCurrUserInfoData(Dishes.this.getWCAppContext().email);
					SQLiteDatabase db = MyHelper.get(Dishes.this).getWritableDatabase();
					db.delete("sessionuser", "sessionid="+sessionid+" and uid="+data._id, null);
					db.close();
					pendingOrder(dishid);
					DataMan.get(Dishes.this).addNewSession(data._id,getWCAppContext().restaurant);
					MyHelper.get(Dishes.this).insertNotify(data._id, sessionowner, data.username+ "已退出聚餐", NOTIFY_QUIT_SESSION, ""+sessionid);
				}
			})
			.setNegativeButton("取消", null)
			.create().show();
	}


	protected void askDifferentRestaurantChoice(long restaurant, long id) {
		final long oldrestaurant=restaurant;
		final long dishid=id;
		
		String[] items={
				"独自在新餐厅点餐",
				"邀请好友来新餐厅点餐",
				"返回原餐厅继续点餐",
		};
		android.content.DialogInterface.OnClickListener listener=new DialogInterface.OnClickListener(){
			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch (which){
				case 0:
					comeHereAlong(dishid);
					break;
				case 1:
					askFriendsComeHere(dishid);
					break;
				case 2:
					backToOldRestaurant(oldrestaurant);
					break;
				}
				dialog.dismiss();
			}
		};
		new AlertDialog.Builder(Dishes.this).setTitle("选择点餐方式").setIcon(R.drawable.icon)
		.setSingleChoiceItems(items, -1, listener)
		.create().show();
	}


	protected void backToOldRestaurant(long oldrestaurant) {
		getWCAppContext().restaurant=oldrestaurant;
		currSql="select *, price || '元' as price,'下单量: '||ordertimes||' 次' as ordertimes from dishes where restaurant="+oldrestaurant;
		refreshListMenu();
		Dishes.this.updateTopBar();
	}


	protected void comeHereAlong(long dishid) {
		long sessionid=getWCAppContext().sessionid;
		
		UserInfoData data = MyHelper.get(Dishes.this).getCurrUserInfoData(getWCAppContext().email);
		Cursor s=listdb.rawQuery("select * from restaurants where _id ="+getWCAppContext().restaurant,null);
		s.moveToFirst();
		Cursor c=listdb.rawQuery("select uid from sessionuser where uid != "+data._id+" and  sessionid="+getWCAppContext().sessionid, null);
		while (c.moveToNext()){
			MyHelper.get(Dishes.this).insertNotify(data._id, c.getLong(0), "发起人已解散 "+s.getString(1)+" 聚餐", NOTIFY_DISMISS_ORDER, ""+getWCAppContext().sessionid);
		}
		c.close();
		s.close();
		
		SQLiteDatabase wdb = MyHelper.get(Dishes.this).getWritableDatabase();
		ContentValues v=new ContentValues();
		v.put("restaurant", getWCAppContext().restaurant);
		wdb.update("sessions",  v, "_id="+sessionid, null);
		wdb.delete("sessiondish", "sessionid="+sessionid, null);
		wdb.delete("sessionuser", "sessionid="+sessionid, null);
		wdb.close();
		updateBtnOrderLabel();
		DataMan.get(Dishes.this).addOrder(Dishes.this.getWCAppContext().sessionid,dishid,data._id);
	}


	protected void askFriendsComeHere(long dishid) {
		long sessionid=getWCAppContext().sessionid;
		
		UserInfoData data = MyHelper.get(Dishes.this).getCurrUserInfoData(getWCAppContext().email);
		Cursor s=listdb.rawQuery("select * from restaurants where _id ="+getWCAppContext().restaurant,null);
		s.moveToFirst();
		Cursor c=listdb.rawQuery("select uid from sessionuser where uid != "+data._id+" and  sessionid="+getWCAppContext().sessionid, null);
		while (c.moveToNext()){
			MyHelper.get(Dishes.this).insertNotify(data._id, c.getLong(0), data.username+"更改聚餐地点到"+s.getString(1), NOTIFY_PLACE_CHANGED, ""+getWCAppContext().sessionid);
		}
		c.close();
		s.close();
		
		SQLiteDatabase wdb = MyHelper.get(Dishes.this).getWritableDatabase();
		ContentValues v=new ContentValues();
		v.put("restaurant", getWCAppContext().restaurant);
		wdb.update("sessions",  v, "_id="+sessionid, null);
		wdb.delete("sessiondish", "sessionid="+sessionid, null);
		wdb.close();
		updateBtnOrderLabel();
		DataMan.get(Dishes.this).addOrder(Dishes.this.getWCAppContext().sessionid,dishid,data._id);
	}


	protected void showSessionDishModifyDialog(long arg3) {
		final long dishid=arg3;
		Cursor c=listdb.rawQuery("select * from sessiondish where dishid="+dishid+" and sessionid="+getWCAppContext().sessionid, null);
		if (!c.moveToFirst()) {
			c.close();
			return;
		}
		final LinearLayout l=(LinearLayout) View.inflate(Dishes.this, R.layout.modifyorder, null);
		TextView v=(TextView) l.findViewById(R.id.txtNow);
		v.setText(""+c.getString(5));
		Button btnPlus=(Button) l.findViewById(R.id.btnplus);
		btnPlus.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				//Cursor c=listdb.rawQuery("select * from sessiondish where dishid="+dishid+" and sessionid="+getWCAppContext().sessionid, null);
				//c.moveToFirst();
				TextView v=(TextView) l.findViewById(R.id.txtNow);
				v.setText(""+(Integer.parseInt(v.getText().toString())+1));
				//c.close();
			}
		});
		Button btnMinus=(Button) l.findViewById(R.id.btnminus);
		btnMinus.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				//Cursor c=listdb.rawQuery("select * from sessiondish where dishid="+dishid+" and sessionid="+getWCAppContext().sessionid, null);
				//c.moveToFirst();
				TextView v=(TextView) l.findViewById(R.id.txtNow);
				int total=Integer.parseInt(v.getText().toString())-1;
				if (total<1) total=1;
				v.setText(""+total);
				//c.close();
			}
		});
		c.close();
		Cursor s=listdb.rawQuery("select name||' '||price||'元' as title from dishes where _id="+dishid, null);
		s.moveToFirst();
		String title=s.getString(0);
		s.close();
		new AlertDialog.Builder(Dishes.this)
			.setTitle(title)
			.setView(l)
			.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					UserInfoData userdata = MyHelper.get(Dishes.this).getCurrUserInfoData(getWCAppContext().email);
					SQLiteDatabase db = MyHelper.get(Dishes.this).getWritableDatabase();
					TextView v=(TextView) l.findViewById(R.id.txtNow);
					ContentValues values=new ContentValues();
					values.put("fromuid", userdata._id);
					values.put("total", Integer.parseInt(v.getText().toString()));
					db.update("sessiondish", values, "dishid="+dishid+" and sessionid="+getWCAppContext().sessionid, null);
					db.close();
					Toast.makeText(Dishes.this, "修改成功!", Toast.LENGTH_SHORT).show();
					refreshListMenu();
					refreshOrder();
					updateBtnOrderLabel();
				}
			})
			.setNegativeButton("取消", null).create().show();
	}


	protected void pendingOrder(long id) {
		pendList.add(id);
	}

	@Override
	public void onDestroy(){
		listdb.close();
		super.onDestroy();
	}
	
	protected int getLayoutRes() {
		return R.layout.dishes;
	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

}
